package com.py.credit.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.constant.ResourcePath;
import com.py.credit.entity.AuthorizonConfig;
import com.py.credit.entity.Column;
import com.py.credit.entity.Database;
import com.py.credit.entity.Dept;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.TableResult;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.AuthorizationSearchTableFieldEnum;
import com.py.credit.service.AuthorizationConfigService;
import com.py.credit.service.DbService;
import com.py.credit.service.DeptService;
import com.py.credit.service.GetRoleService;
import com.py.credit.service.RemoteBaseService;
import com.py.credit.service.TableService;
import com.py.credit.utils.DateUtils;
import com.py.credit.utils.ExcelUtil;
import com.py.credit.utils.FileUtil;
import com.py.credit.utils.FileUtils;
import com.py.credit.utils.MapCache;
import com.py.framework.core.annotation.IgnoreAuthority;
import com.py.framework.core.common.Page;
import com.py.framework.core.entity.SysUserEntity;
import com.py.framework.core.exception.ServiceException;
import com.py.framework.core.helper.HttpServletHelper;

@RestController
@RequestMapping("/authorizationSearch")
public class AuthorizationSearchController {

	@Autowired
	private DeptService deptService;

	@Autowired
	private RemoteBaseService remoteBaseService;

	@Autowired
	private TableService tableService;

	@Autowired
	private DbService dbService;

	@Autowired
	private AuthorizationConfigService authorizationConfigService;
	
	@Autowired
    private GetRoleService getRoleService;

	private final static String FRONT_TABLE_AUTH__ID = "authListTable";

	@Value("${absolutepath}")
	private String absolutepath;

	/**
	 * 顶级部门
	 * 
	 * @return
	 */

	@RequestMapping(value = "/getTopLevelDept.json")
	public RestServiceResult<List<Dept>> getTopLevelDept() {

		return new RestServiceResult<List<Dept>>(deptService.getTopLevelDept());

	}

	/**
	 * 获取资源
	 * 
	 * @return
	 */

	@RequestMapping(value = "/getCubes.json")
	public RestServiceResult<List<Map<String, Object>>> getCubes(
			@RequestParam(value = "deptId", defaultValue = "", required = true) String deptId,
			@RequestParam(value = "kId", defaultValue = "", required = true) String kId) {

		List<Map<String, Object>> tableList = tableService.getTableList(kId, deptId, "YZS");

		return new RestServiceResult<List<Map<String, Object>>>(tableList);

	}

	/**
	 * 添加授权
	 * 
	 * @return
	 * @throws IOException
	 * @throws IllegalStateException
	 */

	@RequestMapping(value = "/add.json")
	public RestServiceResult<Object> add(AuthorizonConfig authorizonConfig,
			@RequestParam(value = "cubes", defaultValue = "", required = true) String cubes,
			@RequestParam(value = "subjects", defaultValue = "", required = true) String subjects,
			@RequestParam(value = "file", defaultValue = "", required = true) CommonsMultipartFile file,HttpServletRequest request)
			throws IllegalStateException, IOException {

		int id = authorizationConfigService.add(authorizonConfig, cubes, subjects);
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));

	    SysUser userInfo = user.getData();
	    String deptName = userInfo.getOfficeName();
		String fileType = null;

		String fileName = null;

		if (file != null) {

			// 获取文件后缀
			if (file.getOriginalFilename().contains(".")) {
				fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."),
						file.getOriginalFilename().length());

				fileName = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."));
			} else {

				throw new ServiceException("附件文件后缀名不能为空");
			}

			String dir = absolutepath + ResourcePath.AUTHORIZATION_ATTACHMENT_DIR + id + File.separator;

			if (!new File(dir).exists()) {

				new File(dir).mkdirs();

			}

			file.transferTo(new File(dir + fileName + fileType));

		}

		authorizonConfig.setApplyEvidence(absolutepath + ResourcePath.AUTHORIZATION_ATTACHMENT_DIR + id + File.separator+fileName + fileType);
		authorizationConfigService.update(authorizonConfig);

		return new RestServiceResult<Object>();

	}

	@RequestMapping(value = "/del.json")
	public RestServiceResult<Object> del(@RequestParam(value = "ids", defaultValue = "", required = true) String ids) {

		String[] tableIds = ids.split(",");

		for (String id : tableIds) {

			authorizationConfigService.delete(Integer.valueOf(id));
		}

		return new RestServiceResult<Object>();

	}

	@RequestMapping(value = "/getUserByTopDeptId.json")
	public RestServiceResult<List<SysUserEntity>> getUserByTopDeptId(
			@RequestParam(value = "deptId", defaultValue = "", required = true) String deptId) {

		RestServiceResult<List<SysUserEntity>> users = remoteBaseService.getAllUserByTopDeptId(deptId);

		return users == null ? new RestServiceResult<List<SysUserEntity>>() : users;

	}

	/**
	 * 当前用户授权的查询主体
	 * 
	 * @param kId
	 * @param request
	 * @return
	 */

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getAuthorizonSubjectList.json")
	public RestServiceResult<Object> getAuthorizonSubjectList(
			@RequestParam(value = "kId", defaultValue = "", required = true) String kId,
			@RequestParam(value = "keyword", defaultValue = "", required = true) String keyword,
			HttpServletRequest request) {

		List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();

		Map<String, Object> data = new HashMap<String, Object>();

		data.put("records", result);

		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));

		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {

			SysUser userInfo = user.getData();

			if (null != userInfo && userInfo.getId() != null) {

				List<Map<String, Object>> all = authorizationConfigService.getAuthorizonSubjectList(userInfo.getId(),
						kId, keyword);

				// List<Map<String, String>> cubes =
				// authorizationConfigService.getAuthorizonCubeList(userInfo.getId(),
				// kId);
				Map<String, Map<String, Object>> unique = new HashMap<String, Map<String, Object>>();
				for (Map<String, Object> map : all) {

					String subjectName = (String) map.get("subjectName");
					String subjectCode = (String) map.get("subjectCode");
					String cubeName = (String) map.get("cubeName");
					Integer cubeId = (Integer) map.get("cubeId");
					Date expiryDate = (Date) map.get("expiryDate");

					String key = subjectName + "_" + subjectCode;

					if (unique.containsKey(key)) {

						Map<String, Object> dataMap = unique.get(key);

						List<String> cubes = (ArrayList<String>) dataMap.get("cubeNames");

						List<Integer> cubeIds = (ArrayList<Integer>) dataMap.get("cubeIds");

						if (!cubes.contains(cubeName)) {
							cubes.add(cubeName);
							cubeIds.add(cubeId);
						}

					} else {

						Map<String, Object> dataMap = new HashMap<String, Object>();
						List<String> cubes = new ArrayList<String>();
						cubes.add(cubeName);
						List<Integer> cubeIds = new ArrayList<Integer>();
						cubeIds.add(cubeId);
						dataMap.put("cubeNames", cubes);
						dataMap.put("cubeIds", cubeIds);

						dataMap.put("expiryDate", expiryDate);
						dataMap.put("kId", kId);
						dataMap.put("subjectName", subjectName);
						dataMap.put("subjectCode", subjectCode);
						dataMap.put("cubeName", cubeName);
						dataMap.put("cubeId", cubeId);
						unique.put(key, dataMap);
						result.add(dataMap);

					}

				}

				data.put("records", result);

			} else {

				ExceptionLogger.error("AuthorizationSearchController#getAuthorizonSubjectList", "未获取到当前用户信息！");

			}

		} else {

			ExceptionLogger.error("AuthorizationSearchController#getAuthorizonSubjectList", "未获取到当前用户信息！");
		}

		return new RestServiceResult<Object>(data);

	}

	/**
	 * 授权查询详情
	 * 
	 * @param keyword
	 * @param auTable
	 * @param kId
	 * @param request
	 * @return
	 */

	@RequestMapping(value = "/getDetail.json")
	public RestServiceResult<List<TableResult>> getDetail(
			@RequestParam(value = "keyword1", defaultValue = "", required = true) String keyword1,
			@RequestParam(value = "keyword2", defaultValue = "", required = true) String keyword2,
			@RequestParam(value = "auTable", defaultValue = "", required = true) String auTable,
			@RequestParam(value = "kId", defaultValue = "", required = true) int kId, HttpServletRequest request) {

		String userName = "";
		String deptName = "";

		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));

		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {

			SysUser userInfo = user.getData();

			if (null != userInfo && userInfo.getId() != null) {

				userName = userInfo.getUsername();
				deptName = userInfo.getOfficeName();
			} else {

				ExceptionLogger.error("AuthorizationSearchController#getDetail", "未获取到当前用户信息！");

			}

		} else {

			ExceptionLogger.error("AuthorizationSearchController#getDetail", "未获取到当前用户信息！");
		}

		RestServiceResult<List<TableResult>> restServiceResult = new RestServiceResult<List<TableResult>>();

		if (auTable != null) {

			List<TableResult> result = new ArrayList<TableResult>();

			String[] auTableName = auTable.split(",");

			if (kId == 100001) {

				result = authorizationConfigService.getDetail(kId, keyword2, auTableName, userName,deptName);

			} else {

				result = authorizationConfigService.getDetail(kId, keyword1, auTableName, userName,deptName);

			}

			restServiceResult.setData(result);

		} else {

			restServiceResult.setData(new ArrayList<TableResult>());
		}

		return restServiceResult;

	}

	@RequestMapping(value = "/downloadFile.json")
	public void downloadFile(@RequestParam(value = "id", defaultValue = "", required = true) int id,
			HttpServletResponse response) {

		AuthorizonConfig authorizonConfig = authorizationConfigService.getById(id);

		String dir = absolutepath + ResourcePath.AUTHORIZATION_ATTACHMENT_DIR + authorizonConfig.getId()
				+ File.separator + authorizonConfig.getApplyEvidence();

		if (!new File(dir).exists()) {

			throw new ServiceException("附件不存在,请重新上传");

		}

		FileUtil.downloadFile(dir, response);

	}

	/**
	 * 文件导入
	 * 
	 * @param file
	 * @return
	 * @throws Exception
	 */

	@RequestMapping(value = "/addByFile.json")
	public RestServiceResult<Object> add(
			@RequestParam(value = "file", defaultValue = "", required = true) CommonsMultipartFile file,
			@RequestParam(value = "attachment", defaultValue = "", required = true) CommonsMultipartFile attachment)
			throws Exception {

		if (file == null || attachment == null) {
			throw new ServiceException("数据文件和附件不能为空");
		}
		String fileName = null;

		if (attachment.getOriginalFilename().contains(".")) {

			fileName = attachment.getOriginalFilename().substring(0, attachment.getOriginalFilename().lastIndexOf("."));

			fileName += attachment.getOriginalFilename().substring(attachment.getOriginalFilename().lastIndexOf("."),
					attachment.getOriginalFilename().length());

		} else {

			throw new ServiceException("附件文件后缀名不能为空");
		}

		RestServiceResult<Object> restServiceResult = new RestServiceResult<Object>();
		String fileDir = absolutepath + ResourcePath.AUTHORIZATION_DIR + DateUtils.getCurrentTimeNumber()
				+ File.separator;

		File dirPath = new File(fileDir);

		if (!dirPath.exists()) {

			dirPath.mkdirs();

		}

		RestServiceResult<List<SysUserEntity>> user = remoteBaseService.getAllUserByTopDeptId(null);

		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {

			List<SysUserEntity> userInfo = user.getData();

			if (null != userInfo && userInfo.size() > 0) {

				List<Map<String, String>> cubes = authorizationConfigService.getSharingContentCubesByType("YZS");

				List<Database> dbList = dbService.getDbList(null);

				String filePath = fileDir + ResourcePath.AUTHORIZATION_FILE;
				// 保存文件,等待解压
				FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(filePath));
				Set<String> ids = authorizationConfigService.parseFileToDB(filePath, userInfo, cubes, dbList, fileName);

				for (String id : ids) {

					String dir = absolutepath + ResourcePath.AUTHORIZATION_ATTACHMENT_DIR + id + File.separator;

					if (!new File(dir).exists()) {

						new File(dir).mkdirs();

					}

					FileCopyUtils.copy(attachment.getInputStream(), new FileOutputStream(dir + fileName));

				}

			} else {

				throw new ServiceException("未获取到用户信息----》 remoteBaseService#getAllUserByTopDeptId");

			}

		} else {

			throw new ServiceException("获取用户信息失败----》 remoteBaseService#getAllUserByTopDeptId");
		}
		restServiceResult.setMsg("导入成功");
		return restServiceResult;

	}

	/**
	 * 申请列表
	 * 
	 * @param deptId
	 * @param condition
	 * @param page
	 * @param request
	 * @return
	 */

	@RequestMapping(value = "/getAuthList.json")
	public RestServiceResult<List<Map<String, Object>>> getAuthList(
			@RequestParam(value = "deptId", defaultValue = "", required = true) String deptId,
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page,
			HttpServletRequest request) {
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		String token = HttpServletHelper.getUserToken(request);
		String rolename="";
		String userName="";
		String[] configColumns = null;
		SysUser userInfo = user.getData();
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			if (null != userInfo) {
				//获取当前用户的角色
				List<HashMap<String,Object>> rolenames =  getRoleService.getRolesByUserId(userInfo.getId(), token).getData();   
		        for (Map<String, Object> map : rolenames) {         	
		            for (String key : map.keySet()) {
		           	 if(key.equals("roleName")) {
		           		 if(map.get(key)!=null) {
		           			 rolename = (String) map.get(key);
		           		 }
		           		 break;
		           	 }
		            }
		        }
				if(rolename.equals("系统管理员")) {
					userName="";
				}else {
					userName=userInfo.getUsername();
				}
				configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + FRONT_TABLE_AUTH__ID);
			} else {

				ExceptionLogger.error("AuthorizationSearchController#getAuthList", "未获取到当前用户信息！");
			}

		} else {

			ExceptionLogger.error("AuthorizationSearchController#getAuthList", "未获取到当前用户信息！");
		}

		List<String> showColumns = (configColumns == null || configColumns.length == 0)
				? AuthorizationSearchTableFieldEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
		String[] additionalColumns = { "id" };			
		List<Map<String, Object>> tableList = authorizationConfigService.getByConditionForPage(userName, showColumns,
				additionalColumns, condition, page);
		return new RestServiceResult<List<Map<String, Object>>>(page.getTotalCount(), tableList);
	}

	@RequestMapping(value = "/addShowColunms.json")
	public RestServiceResult<String> addShowColunms(@RequestParam(value = "columns", required = true) String[] columns,
			HttpServletRequest request) {

		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));

		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {

			SysUser userInfo = user.getData();

			if (null != userInfo) {

				MapCache.set(userInfo.getId() + "_" + FRONT_TABLE_AUTH__ID, columns);
			} else {

				ExceptionLogger.error("AuthorizationSearchController#addShowColunms", "未获取到当前用户信息！");
			}

		} else {

			ExceptionLogger.error("AuthorizationSearchController#addShowColunms", "未获取到当前用户信息！");
		}

		return new RestServiceResult<String>();
	}

	@RequestMapping(value = "/getOptionalColums.json")
	public RestServiceResult<List<OptionalColumn>> getOptionalColums() {

		return new RestServiceResult<List<OptionalColumn>>(AuthorizationSearchTableFieldEnum.getOptionalColumns());

	}

	@RequestMapping(value = "/getAdvancedConditionColumns.json")
	public RestServiceResult<List<OptionalColumn>> getAdvancedConditionColumns() {

		return new RestServiceResult<List<OptionalColumn>>(
				AuthorizationSearchTableFieldEnum.getAdvancedConditionColumns());

	}

	@RequestMapping(value = "/export.json")
	public void export(@RequestParam(value = "columnEN", defaultValue = "", required = true) String columnEN,
			@RequestParam(value = "deptId", defaultValue = "", required = true) String deptId,
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page,
			HttpServletRequest request,HttpServletResponse response) throws IOException {
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		String token = HttpServletHelper.getUserToken(request);
		SysUser userInfo = user.getData();
		String rolename=userInfo.getUsername();
		
		String[] configColumns = null;
		
		page.setLimit(1000);

		List<String> showColumns = JSONArray.parseArray(columnEN, String.class);
		List<Map<String, Object>> tableList = authorizationConfigService.getByConditionForPage(rolename, showColumns,
				null, condition, page);

		List<OptionalColumn> optionalColumns = AuthorizationSearchTableFieldEnum.getOptionalColumns();

		ExcelUtil.downloadExcel(response, tableList, "授权列表", "授权列表", showColumns, optionalColumns);

	}

	@RequestMapping(value = "/getAuthDetail.json")
	public RestServiceResult<Map<String, Object>> getAuthDetail(
			@RequestParam(value = "id", defaultValue = "", required = true) int id) {

		Map<String, Object> detail = authorizationConfigService.getAuthDetail(id);

		return new RestServiceResult<Map<String, Object>>(detail);
	}

	@IgnoreAuthority
	@RequestMapping("/downloadTemplate.json")
	public void downloadTemplate(HttpServletResponse response) throws IOException {

		FileUtils.downloadFile(this.getClass().getResource("/授权导入模板.xlsx").getPath(), response);

	}
	
	/**
	 * 待审核数据
	 * @param applicant_name
	 * @param request
	 * @return
	 */
	@IgnoreAuthority
	@RequestMapping("/selectShdata.json")
	public RestServiceResult<List<Map<String, String>>> selectShdata(
			@RequestParam(value = "applicant_name", defaultValue = "", required = true) String applicant_name,
			@RequestParam(value = "apply_dept_name", defaultValue = "", required = true) String apply_dept_name,
			Page page,	
			HttpServletRequest request) {
		RestServiceResult<List<Map<String, String>>> result = new RestServiceResult<>();
	        String token = HttpServletHelper.getUserToken(request);
	     // 获取当前用户信息
			RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(token);
			String rolename=user.getData().getRoleName();
			String deptId;
			
	        if(rolename.equals("系统管理员")) {
	        	deptId = "";
	        }else {
	        	 deptId = String.valueOf(user.getData().getOfficeId());
	        }
	       
		try {
			List<Map<String, String>> data = authorizationConfigService.selectShdataForPage(applicant_name,deptId,apply_dept_name,page);
			result.setCount(page.getTotalCount());
			result.setData(data);
		} catch (Exception e) {
			   result.setCode(RestServiceResult.CODE_UNKNOW);
	            result.setMsg("待审核数据获取失败");
		}
		
		 return result;
	
	}
	/**
	 * 审核状态变更
	 * @param id
	 * @param apply_status
	 * @param request
	 * @return
	 */
	@IgnoreAuthority
	@RequestMapping("/updateApplyStatus.json")
	public RestServiceResult<Object> updateApplyStatus(
			@RequestParam(value = "id", defaultValue = "", required = true) String id,
			@RequestParam(value = "shyj", defaultValue = "", required = true) String shyj,
			@RequestParam(value = "apply_status", defaultValue = "", required = true) String apply_status,
			HttpServletRequest request) {
		RestServiceResult<Object> result = new RestServiceResult<>();
		try {
			authorizationConfigService.updateApplyStatusByID(id,apply_status,shyj);
		} catch (Exception e) {
			   result.setCode(RestServiceResult.CODE_UNKNOW);
	            result.setMsg("审核失败");
		}
		
		 return result;
	
	}
	/**
	 * 下载文件
	 * 
	 * @param response
	 * @throws IOException
	 */
	@IgnoreAuthority
	@RequestMapping("/exportsqcl.json")
	public void exportsqcl(String url, HttpServletResponse response) throws IOException {
		
		FileUtils.downloadFile(URLDecoder.decode(url, "UTF-8"), response);

	}
}
